package com.runen.wnhz.runen.ui.fragment.minem;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.NetStateUtils;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.MyCourseEntity;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.di.component.DaggerCourseComponent;
import com.runen.wnhz.runen.di.module.CourseModule;
import com.runen.wnhz.runen.presenter.Contart.CourseContart;
import com.runen.wnhz.runen.presenter.iPresenter.ICoursePersenter;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.CourseAdapter;
import com.runen.wnhz.runen.ui.fragment.BaseFragment;
import com.runen.wnhz.runen.widget.TitleBuilder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018-04-12.
 */

public class DownloadedFragment extends BaseFragment<ICoursePersenter> implements CourseContart.View, View.OnClickListener {

    @BindView(R.id.rv_downloaded)
    RecyclerView recyclerView;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout smartRefreshLayout;


    private int page = 0;

    private UserBean reqeustUser;

    private CourseAdapter courseAdapter;

    private boolean hasNextPage = false;

    private int currentPage = 0;

    private int totalPage = 0;

    private boolean isRefresh = false;

    private boolean isLoadMore = false;

    private List<MyCourseEntity.DataBean.ListBean> listBeanList;

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {
        DaggerCourseComponent.builder().applicationComponent(appComponent)
                .courseModule(new CourseModule(this))
                .build().intject(this);
    }

    @Override
    protected int getLayoutView() {
        return R.layout.downloaded_fragment_layout;
    }

    private void getLearningLessonData(String pageNum){
        if(getToken() != null) {
            FormBody formBody = new FormBody.Builder().add("token", getToken()).add("type","2").add("page",pageNum).build();
            Request request = new Request.Builder().url(NetUtils.USER_LESSON).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                            refreshOrLoadMoreFailed();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        handleUserLesson(response);
                    } catch (IOException e) {
                        e.printStackTrace();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showToast("数据请求出现异常");
                                refreshOrLoadMoreFailed();
                            }
                        });
                    }
                }
            });
        }
    }

    private void handleUserLesson(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                final String json = responseBody.string();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MyCourseEntity courseEntity = new Gson().fromJson(json, MyCourseEntity.class);
                        if (courseEntity != null) {
                                if ("1".equals(courseEntity.getRe())) {
                                    MyCourseEntity.DataBean dataBean = courseEntity.getData();
                                    totalPage = Integer.parseInt(dataBean.getSum_page());
                                    currentPage = Integer.parseInt(dataBean.getSum_page());
                                    String isPage = dataBean.getIs_page();
                                    hasNextPage = "1".equals(isPage);
                                    List<MyCourseEntity.DataBean.ListBean> list = courseEntity.getData().getList();
                                    if (isRefresh) {
                                        if (list.size() != 0) {
                                            currentPage = 0;
                                        }
                                        if (listBeanList.size() != 0) {
                                            listBeanList.clear();
                                        }
                                        listBeanList.addAll(list);
                                        if (courseAdapter == null) {
                                            courseAdapter = new CourseAdapter(listBeanList, getContext());
                                            recyclerView.setAdapter(courseAdapter);
                                        } else {
                                            courseAdapter.notifyDataSetChanged();
                                        }
                                        isRefresh = false;
                                        smartRefreshLayout.finishRefresh(true);
                                        return;
                                    }
                                    if (isLoadMore) {
                                        if (list.size() != 0) {
                                            currentPage = currentPage + 1;
                                        }
                                        listBeanList.addAll(list);
                                        if (courseAdapter == null) {
                                            courseAdapter = new CourseAdapter(listBeanList, getContext());
                                            recyclerView.setAdapter(courseAdapter);
                                        } else {
                                            courseAdapter.notifyDataSetChanged();
                                        }
                                        isLoadMore = false;
                                        smartRefreshLayout.finishLoadMore(true);
                                        return;
                                    }
                                    currentPage = 0;
                                    if(listBeanList.size() != 0){
                                        listBeanList.clear();
                                    }
                                    listBeanList.addAll(list);
                                    courseAdapter = new CourseAdapter(listBeanList, getContext());
                                    recyclerView.setAdapter(courseAdapter);
                                } else if ("0".equals(courseEntity.getRe())) {
                                    ToastUtil.showToast(courseEntity.getInfo());
                                } else if ("-1".equals(courseEntity.getRe())) {
                                    ToastUtil.showToast(courseEntity.getInfo());
                                    startActivity(new Intent(getActivity(), LoginForPersonalActivity.class));
                                }
                            }
                        }
                });

            }
        }
    }

    private void refreshOrLoadMoreFailed(){
        if(isLoadMore){
            smartRefreshLayout.finishLoadMore(false);
            isLoadMore = false;
        }
        if(isRefresh){
            smartRefreshLayout.finishRefresh(false);
            isRefresh = false;
        }
    }

    @Override
    public void initUiAndListener(View view) {
        reqeustUser = ACacheUtlis.getInstance().getReqeustUser(getContext());
        listBeanList = new ArrayList<>();
    }

    @Override
    public void onStart() {
        super.onStart();
//        mPresenter.getContent();
    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        setToolBarVisible(View.GONE);
    }

    @Override
    public void showLoadding() {

    }

    @Override
    public void dimissLoding() {

    }

    @Override
    public void showErrorMessage(String msg) {
//        ToastUtil.showToast(msg);
    }

    @Override
    public void onTitleButtonClicked(TitleBuilder.TitleButton clicked) {

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onTokenError(String msg) {
        super.onTokenError(msg);
        startActivity(new Intent(getActivity(), LoginForPersonalActivity.class));
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListener();
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(getActivity() != null && getUserVisibleHint()){
            getLearningLessonData(String.valueOf(currentPage));
        }
    }

    private void setListener(){
        smartRefreshLayout.setEnableAutoLoadMore(false);
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if(NetStateUtils.isNetworkAvalible(getActivity())){
                    if(hasNextPage){
                        int tempCurrentPage = currentPage + 1;
                        isLoadMore = true;
                        getLearningLessonData(String.valueOf(tempCurrentPage));
                    }else{
                        ToastUtil.showToast("暂无更多数据");
                        smartRefreshLayout.finishLoadMore(true);
                    }
                }else{
                    ToastUtil.showToast("暂无网络");
                    smartRefreshLayout.finishLoadMore(false);
                }

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if(NetStateUtils.isNetworkAvalible(getActivity())){
                    int tempCurrentPage = 0;
                    isRefresh = true;
                    getLearningLessonData(String.valueOf(tempCurrentPage));
                }else{
                    ToastUtil.showToast("暂无网络");
                    smartRefreshLayout.finishRefresh(false);
                }
            }
        });
    }


    @Override
    public String getType() {
        return "2";
    }

    @Override
    public String getPage() {
        return "0";
    }


    @Override
    public String getToken() {
        return reqeustUser.getToken();
    }

    //    @Override
    public void showLoginError(String info) {
        ToastUtil.showToast(info);
    }

    @Override
    public void onSuccess(MyCourseEntity data) {

//        courseAdapter = new CourseAdapter(data.getData().getList(), getContext());
//
//        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//
//        recyclerView.setAdapter(courseAdapter);
    }
}
